package com.bigdata.service.mysql.impl;

import com.bigdata.common.em.CommonEnum;
import com.bigdata.model.Result;
import com.bigdata.model.SearchModel;
import com.bigdata.model.User;
import com.bigdata.mysql.dao.JkfwUserMapper;
import com.bigdata.mysql.dao.JkfwUserRoleMapper;
import com.bigdata.mysql.entity.*;
import com.bigdata.service.mysql.JkfwUserRoleService;
import com.bigdata.service.mysql.JkfwUserService;
import com.bigdata.service.mysql.base.impl.BaseService;
import com.bigdata.utils.StringUtil;
import com.bigdata.utils.shiro.ShiroUtils;
import com.bigdata.vo.VoJkfwUser;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.catalina.webresources.JarWarResource;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * JkfwUser的服务接口的实现类
 *
 * @author
 */
@Service
public class JkfwUserServiceImpl extends BaseService<JkfwUserMapper, JkfwUser, JkfwUserExample> implements JkfwUserService {
    private final Logger log = LogManager.getLogger(this.getClass());

    @Autowired
    JkfwUserRoleService jkfwUserRoleService;

    /**
     * @param searchModel
     * @return com.bigdata.model.Result
     * @Author lly
     * @Date 2019/7/15 0015
     * @Description 查询分页数据
     */
    @Override
    public Result queryPage(SearchModel searchModel) {
        Page<JkfwUser> page = PageHelper.startPage(searchModel.getPageNumber(), searchModel.getPageSize());
        JkfwUserExample example = new JkfwUserExample();
        JkfwUserExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNoneBlank(searchModel.getS_name())) {
            criteria.andUsernameLike("%" + searchModel.getS_name() + "%");
        }
        dao.selectByExample(example);
        Result res = Result.pageOk(page.getResult());
        res.setTotal(page.getTotal());
        res.setPages((long) page.getPages());
        return res;
    }

    @Override
    public Result selectByUserid(String id) {
        JkfwUser user = dao.selectByPrimaryKey(id);
        JkfwUserRoleExample example = new JkfwUserRoleExample();
        example.createCriteria().andUserIdEqualTo(id);
        List<JkfwUserRole> roles = jkfwUserRoleService.selectByExample(example);
        VoJkfwUser voJkfwUser = new VoJkfwUser(user, roles);
        Result result = new Result();
        result.setData(voJkfwUser);
        return result;
    }

    /**
     * @param user
     * @return com.bigdata.model.Result
     * @Author lly
     * @Date 2019/7/15 0015
     * @Description 添加用户
     */
    @Override
    public Result addUser(JkfwUser user) {
        JkfwUserExample example = new JkfwUserExample();
        example.createCriteria().andUsernameEqualTo(user.getUsername());
        List<JkfwUser> list = dao.selectByExample(example);
        if (list.size() == 0) {
            User sesusr = ShiroUtils.getSysUser();
            user.setUserId(UUID.randomUUID().toString().replace("-", ""));
            user.setCreateTime(new Date());
            user.setStatus(user.getStatus());
            user.setCreateUserId(sesusr.getUserId());
            user.setSalt(User.randomSalt());
            user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
            dao.insert(user);
        } else {
            return Result.fail("用户名已存在！");
        }
        return Result.ok();
    }

    /**
     * @param vouser
     * @return com.bigdata.model.Result
     * @Author lly
     * @Date 2019/7/15 0015
     * @Description 添加用户和权限
     */
    @Override
    @Transactional(readOnly = false)
    public Result addUserRole(VoJkfwUser vouser) {
        JkfwUserExample example = new JkfwUserExample();
        example.createCriteria().andUsernameEqualTo(vouser.getUsername());
        List<JkfwUser> list = dao.selectByExample(example);
        if (list.size() == 0) {
            User sesusr = ShiroUtils.getSysUser();
            JkfwUser user = vouser.covrJkfwUser();
            user.setUserId(UUID.randomUUID().toString().replace("-", ""));
            user.setCreateTime(new Date());
            user.setStatus(user.getStatus());
            user.setCreateUserId(sesusr.getUserId());
            user.setSalt(User.randomSalt());
            user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
            dao.insert(user);
            List<String> roles = StringUtil.splitList(vouser.getRoleids());
            jkfwUserRoleService.addUserRoleids(roles, user);
        } else {
            return Result.fail("用户名已存在！");
        }
        return Result.ok();
    }


    @Override
    public Boolean ckUserName(String username) {
        JkfwUserExample example = new JkfwUserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<JkfwUser> list = dao.selectByExample(example);
        if (list.size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param user
     * @return com.bigdata.model.Result
     * @Author lly
     * @Date 2019/7/15 0015
     * @Description 修改用户
     */
    @Override
    public Result updateUser(JkfwUser user) {
        user.setUsername(null);//用户名不允许修改
        JkfwUser us = dao.selectByPrimaryKey(user.getUserId());
        if (us != null) {
            if (StringUtils.isNoneBlank(user.getPassword())) {
                user.setPassword(ShiroUtils.sha256(user.getPassword(), us.getSalt()));
                user.setSalt(null);// 盐不能变
            } else {
                user.setPassword(null);
            }
            dao.updateByPrimaryKeySelective(user);
        } else {
            return Result.fail("用户不存在！");
        }
        return Result.ok();
    }

    /**
     * 修改用户和角色
     *
     * @param * @param user
     * @return com.bigdata.model.Result
     * @author lly
     * @date 2020/3/22 18:38
     */
    @Override
    @Transactional(readOnly = false)
    public Result updateUserRole(VoJkfwUser vuser) {
        JkfwUser user = vuser.covrJkfwUser();
        user.setUsername(null);//用户名不允许修改
        JkfwUser us = dao.selectByPrimaryKey(user.getUserId());
        if (us != null) {
            if (StringUtils.isNoneBlank(user.getPassword())) {
                user.setPassword(ShiroUtils.sha256(user.getPassword(), us.getSalt()));
                user.setSalt(null);// 盐不能变
            } else {
                user.setPassword(null);
            }
            dao.updateByPrimaryKeySelective(user);
            jkfwUserRoleService.deleteUserid(user);
            jkfwUserRoleService.addUserRoleids(StringUtil.splitList(vuser.getRoleids()), user);
        } else {
            return Result.fail("用户不存在！");
        }
        return Result.ok();
    }

    /**
     * @param userid, password
     * @return com.bigdata.model.Result
     * @Author lly
     * @Date 2019/7/15 0015
     * @Description 初始化密码
     */
    @Override
    public Result intPassword(String userid, String password) {
        JkfwUser user = dao.selectByPrimaryKey(userid);
        if (user != null) {
            String salt = user.getSalt();
            JkfwUser us = new JkfwUser();
            us.setUserId(userid);
            us.setPassword(ShiroUtils.sha256(password, salt));
            dao.updateByPrimaryKeySelective(us);
        } else {
            return Result.fail("用户不存在！");
        }
        return Result.ok();
    }

    /**
     * @param username
     * @return com.bigdata.mysql.entity.JkfwUser
     * @Author lly
     * @Date 2019/7/11 0011
     * @Description 用户登录
     */
    @Override
    public JkfwUser queryUserLogin(String username) {
        JkfwUserExample example = new JkfwUserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<JkfwUser> users = dao.selectByExample(example);
        if (users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    /**
     * @param username, pwd
     * @return com.bigdata.model.Result
     * @Author lly
     * @Date 2019/7/18 0018
     * @Description 验证
     */
    @Override
    public Result ckLoginToken(String username, String pwd) {
        JkfwUser user = queryUserLogin(username);
        if (user == null) {
            Result.fail("账户不存在！");
        }
        if (user.getStatus() != CommonEnum.UserStatus.ok.getIdx()) {
            if (user.getStatus() == CommonEnum.UserStatus.lock.getIdx()) {
                return Result.fail("账户已被锁定！");
            } else {
                return Result.fail("账户不存在！");
            }
        }
        if (!user.getPassword().equals(ShiroUtils.sha256(pwd, user.getSalt()))) {
            return Result.fail("密码不正确！");
        }
        User u = new User(user);
        return Result.ok(u);
    }

    /**
     * @param userid
     * @return com.bigdata.model.Result
     * @Author lly
     * @Date 2019/7/15 0015
     * @Description 删除用户
     */
    @Override
    public Result delUser(String userid) {
        dao.deleteByPrimaryKey(userid);
        return Result.ok();
    }
}